package xx;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;

public class RSAUtil {
	public static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";// 算法/模式/填充,如果没有指定模式或填充方式，就使用特定提供者指定的默认模式或默认填充方式。

	/**
	 * 加密
	 */
	public static String RSAEncode(String pubKey, String plainText) {
		try {
			X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(pubKey));
			// RSA对称加密算法
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			// 取公钥匙对象
			PublicKey publicKey = keyFactory.generatePublic(bobPubKeySpec);
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
			// Cipher cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			byte[] doFinal = cipher.doFinal(plainText.getBytes());
			return Base64.encodeBase64String(doFinal);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) throws Exception {
		String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCREeLA4buA/Y6U1n0C/OFnnJzXZ77CaaF81GDawbN5ObYsblLLMMv3+cylPfQmPRfp98eENHBqgTsNuQZq+as5BrfRJSG3gD6KH3nARD9dNl27Nr9cf6lSlTVgBIFu0pJTNvr5P1QRlLA/J5lvc8k5wteYEckpVWgn32fRxGGL6QIDAQAB";
		String PLAIN_TEXT = "911211";
		
		String encodedText = RSAEncode(PUBLIC_KEY, PLAIN_TEXT);
		System.out.println("RSA encoded: " + encodedText);
	}

}